﻿using System;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;

namespace IntegratedOnBordDebug.UDPCore
{
    /// <summary>
    ///   Code adapted from http://www.dijksterhuis.org/encrypting-decrypting-string/
    ///   You MUST replace it with your favourite one if you want privacy
    /// </summary>
    internal class EncryptHelper
    {
        private static readonly UTF8Encoding Encoder = new UTF8Encoding();

        public static string EncryptString(string message, string passphrase) {
            var hashProvider = new MD5CryptoServiceProvider();
            var tdesKey = hashProvider.ComputeHash(Encoder.GetBytes(passphrase));
            var tdesAlgorithm = new TripleDESCryptoServiceProvider {Key = tdesKey, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7};

            var dataToEncrypt = Encoder.GetBytes(message);
            var encryptor = tdesAlgorithm.CreateEncryptor();
            var results = encryptor.TransformFinalBlock(dataToEncrypt, 0, dataToEncrypt.Length);
            tdesAlgorithm.Clear();
            hashProvider.Clear();
            return Convert.ToBase64String(results);
        }

        public static string DecryptString(string message, string passphrase) {
            var hashProvider = new MD5CryptoServiceProvider();
            var tdesKey = hashProvider.ComputeHash(Encoder.GetBytes(passphrase));
            var tdesAlgorithm = new TripleDESCryptoServiceProvider {Key = tdesKey, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7};

            var dataToDecrypt = Convert.FromBase64String(message);
            var decryptor = tdesAlgorithm.CreateDecryptor();
            try {
                var results = decryptor.TransformFinalBlock(dataToDecrypt, 0, dataToDecrypt.Length);
                return Encoder.GetString(results);
            }
            catch (CryptographicException ex) {
#if DEBUG
                Debugger.Break();
#endif
                return ex.Message.Trim();
            }
            finally {
                tdesAlgorithm.Clear();
                hashProvider.Clear();
            }
        }
    }
}